//
//  YAYIMyQRCodeViewController.m
//  YAYIDoctor
//
//  Created by Veer on 16/5/16.
//
//

#import "YAYIMyQRCodeViewController.h"
#import "YAYICertificationViewController.h"

#import "YAYIShareView.h"
#import "YAYIUserinfoModel.h"


#define YAYISalt @"saltsaltsaltsaltsaltsaltdoctorid:"

@interface YAYIMyQRCodeViewController ()

@property (nonatomic, weak) UIImageView *iconView;
@property (nonatomic, weak) UILabel *nameLbl;
@property (nonatomic, weak) UILabel *typeLbl;
@property (nonatomic, weak) UILabel *hospitalNameLbl;
@property (nonatomic, weak) UILabel *addressLbl;
@property (nonatomic, weak) UIImageView *qrCodeView;

/** 没有数据显示 */
@property (nonatomic, weak) UIView *noDataFlagView;
@property (nonatomic, weak) UIImageView *noverfyIconView;
@property (nonatomic, weak) UILabel *flagLbl1;
@property (nonatomic, weak) UIButton *goVerifyBtn;

@property (copy, nonatomic) NSString *hosName;
@property (copy, nonatomic) NSString *hosAddress;

@end

@implementation YAYIMyQRCodeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"我的二维码名片";
    self.view.backgroundColor = [UIColor colorWithWhite:0.965 alpha:1];
    
    [self setupNav];
    
    [self setupSubView];
    [self getHospitlList];
}


- (void)setupNav
{
    // right button
//    UIButton *rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
//    [rightBtn setImage:[UIImage imageNamed:@"shareBtn"] forState:UIControlStateNormal];
//    
//    rightBtn.bounds = CGRectMake(0, 0, 70, 20);
//    rightBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
//    [rightBtn addTarget:self action:@selector(shareClick:) forControlEvents:UIControlEventTouchUpInside];
//    
//    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightBtn];
    
//    self.navigationController.navigationBar.translucent = NO;
//    self.automaticallyAdjustsScrollViewInsets = NO;
}


- (void)setupSubView
{
    
    if (self.userInfoModel.v != 2) {
        [self showNoDataFlag:YES];
        return;
    }else{
    
        [self showNoDataFlag:NO];
    }
    
    UILabel *desLbl = [[UILabel alloc] init];
    desLbl.hidden = YES;
    desLbl.text = @"一键分享到微信好友、朋友圈和微博";
    desLbl.font = [UIFont systemFontOfSize:15];
    desLbl.textColor = YAYIColor(102, 172, 240);
    desLbl.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:desLbl];
    [desLbl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.top.equalTo(@(20 + 64));
    }];
    
    UIView *containView = [[UIView alloc] init];
    containView.backgroundColor = [UIColor whiteColor];
//    containView.layer.borderWidth = 0.5;
//    containView.layer.borderColor = YAYIColor(151, 151, 151).CGColor;
    containView.layer.masksToBounds = YES;
    containView.layer.cornerRadius = 8.0;
    [self.view addSubview:containView];
    [containView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.view);
        make.top.mas_equalTo(64 + 90 * YAYIScreenScale);
        make.height.mas_equalTo(430 * YAYIScreenScale);
        make.width.mas_equalTo(318 * YAYIScreenScale);
    }];
    
    // topView
    UIView *topView = [[UIView alloc] init];
    [containView addSubview:topView];
    [topView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(containView);
        make.top.mas_equalTo(0);
        make.height.mas_equalTo(93 * YAYIScreenScale);
    }];
    
    // 横线
    UIView *hLineView = [[UIView alloc] init];
    hLineView.backgroundColor = YAYIColor(219, 218, 218);
    [containView addSubview:hLineView];
    [hLineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(0.6);
        make.left.right.mas_equalTo(containView);
        make.top.mas_equalTo(topView.mas_bottom);
        
    }];
    
    // 图标
    UIImageView *iconView = [[UIImageView alloc] init];
    iconView.image = [UIImage imageNamed:@"doctor"];
    iconView.layer.masksToBounds = YES;
    iconView.layer.cornerRadius = 30;
    iconView.contentMode = UIViewContentModeScaleAspectFill;
    [topView addSubview:iconView];
    self.iconView = iconView;
    [iconView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(12);
        make.width.height.mas_equalTo(60);
        make.centerY.mas_equalTo(topView);
    }];
    
    // 姓名
    UILabel *nameLbl = [[UILabel alloc] init];
    nameLbl.font = [UIFont systemFontOfSize:17];
    [topView addSubview:nameLbl];
    self.nameLbl = nameLbl;
    [nameLbl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(iconView).offset(-5);
        make.left.mas_equalTo(iconView.mas_right).offset(14);
    }];
    
    // 职称
    UILabel *typeLbl = [[UILabel alloc] init];
    typeLbl.font = [UIFont systemFontOfSize:15];
    typeLbl.textColor = YAYIColor(157, 157, 157);
    [topView addSubview:typeLbl];
    self.typeLbl = typeLbl;
    [typeLbl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(nameLbl);
        make.left.mas_equalTo(nameLbl.mas_right).offset(10);
    }];
    
    // 医院
    UILabel *hospitalNameLbl = [[UILabel alloc] init];
    hospitalNameLbl.text = self.hosName;
    hospitalNameLbl.font = [UIFont systemFontOfSize:15];
    hospitalNameLbl.textColor = YAYIColor(157, 157, 157);
    [topView addSubview:hospitalNameLbl];
    self.hospitalNameLbl = hospitalNameLbl;
    [hospitalNameLbl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(iconView);
        make.left.mas_equalTo(nameLbl);
    }];
    
    // 位置
    UILabel *addressLbl = [[UILabel alloc] init];
    addressLbl.text = self.hosAddress;
    addressLbl.font = [UIFont systemFontOfSize:15];
    addressLbl.textColor = YAYIColor(157, 157, 157);
    [topView addSubview:addressLbl];
    self.addressLbl = addressLbl;
    [addressLbl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(iconView.mas_bottom).offset(5);
        make.left.mas_equalTo(nameLbl);
    }];
    
    // 二维码view
    UIImageView *qrCodeView = [[UIImageView alloc] init];
//    qrCodeView.image = [self getQRCode:@"http://www.baidu.com"];
    [containView addSubview:qrCodeView];
    self.qrCodeView = qrCodeView;
    [qrCodeView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.mas_equalTo(150);
        make.centerX.mas_equalTo(containView);
        make.top.mas_equalTo(topView.mas_bottom).offset(45 * YAYIScreenScale);
    }];
    
    // 二维码view
    UIImageView *qrIconView = [[UIImageView alloc] init];
    qrIconView.image = [UIImage imageNamed:@"personalIcon"];
    [qrCodeView addSubview:qrIconView];
    [qrIconView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.mas_equalTo(40);
        make.centerX.mas_equalTo(qrCodeView);
        make.centerY.mas_equalTo(qrCodeView);
    }];
    
    // 底部lable
    UILabel *tipLbl = [[UILabel alloc] init];
    tipLbl.text = @"扫描上面的二维码，关注医生";
    tipLbl.font = [UIFont systemFontOfSize:16];
    tipLbl.textColor = YAYIColor(107, 178, 242);
    [containView addSubview:tipLbl];
    [tipLbl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(containView).offset(-44 * YAYIScreenScale);
        make.centerX.mas_equalTo(self.view);
    }];
    
    
    NSString *urlStr = [NSString stringWithFormat:@"%@%@", API, self.userInfoModel.avatar];
    NSURL *url = [NSURL URLWithString:urlStr];
    [self.iconView sd_setImageWithURL:url placeholderImage:[UIImage imageNamed:@"doctor"] options:SDWebImageRefreshCached];
    
    self.nameLbl.text = self.userInfoModel.fullname;
    self.typeLbl.text = self.userInfoModel.title;
    
    NSString *qrCodeUrl = [NSString stringWithFormat:@"http://wx.yayi365.cn/reservation/reservation_det.html?doctorid=%ld&hospitalid=%zd", self.userInfoModel.id, self.userInfoModel.defaulthospital];
    self.qrCodeView.image = [self getQRCode:qrCodeUrl];
}


- (void)showNoDataFlag:(BOOL)flag
{
    if (!flag) {
        [self.noDataFlagView removeFromSuperview];
        self.noDataFlagView = nil;
        return;
    }
    
    if (self.noDataFlagView) {
        
        if (self.userInfoModel.v == 1) { // 待处理
            
            self.goVerifyBtn.hidden = YES;
            self.noverfyIconView.image = [UIImage imageNamed:@"resumeState1"];
            self.flagLbl1.text = @"实名认证审核中，请耐心等待";
        }else if (self.userInfoModel.v == 3) { // 认证失败
            
            self.goVerifyBtn.hidden = YES;
            self.noverfyIconView.image = [UIImage imageNamed:@"resumeState2"];
            self.flagLbl1.text = @"实名认证失败，请重新提交或联系客服";
        }
        return;
    }
    UIView *flagView = [[UIView alloc] init];
    flagView.frame = self.view.bounds;
    [self.view addSubview:flagView];
    self.noDataFlagView = flagView;
    
    UIImageView *iconView = [[UIImageView alloc] init];
    iconView.image = [UIImage imageNamed:@"noVerify"];
    iconView.contentMode = UIViewContentModeScaleAspectFit;
    [flagView addSubview:iconView];
    self.noverfyIconView = iconView;
    [iconView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(0);
        make.top.mas_equalTo(64 + 120);
        make.width.mas_equalTo(SCREEN_width);
        make.height.mas_equalTo(120);
    }];
    
    UILabel *flagLbl1 = [[UILabel alloc] init];
    flagLbl1.text = @"实名认证后，您将获得专属的电子名片";
    flagLbl1.font = [UIFont systemFontOfSize:16];
    flagLbl1.textColor = YAYIColor(107, 178, 242);
    flagLbl1.textAlignment = NSTextAlignmentCenter;
    [flagView addSubview:flagLbl1];
    self.flagLbl1 = flagLbl1;
    [flagLbl1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(flagView);
        make.top.equalTo(iconView.mas_bottom).offset(72);
    }];
    
    UILabel *flagLbl2 = [[UILabel alloc] init];
    flagLbl2.text = @"一键分享到微信好友、朋友圈和微博";
    flagLbl2.font = [UIFont systemFontOfSize:14];
    flagLbl2.textColor = YAYIColor(0x9d, 0x9d, 0x9d);
    flagLbl2.textAlignment = NSTextAlignmentCenter;
    [flagView addSubview:flagLbl2];
    [flagLbl2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(flagView);
        make.top.equalTo(flagLbl1.mas_bottom).offset(5);
    }];
    
    UIButton *goVerifyBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [goVerifyBtn setTitle:@"去实名认证" forState:UIControlStateNormal];
    [goVerifyBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [goVerifyBtn setBackgroundImage:[UIImage imageNamed:@"register_button_normal"] forState:UIControlStateNormal];
    [goVerifyBtn addTarget:self action:@selector(onGoVerifyBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [flagView addSubview:goVerifyBtn];
    self.goVerifyBtn = goVerifyBtn;
    [goVerifyBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(20);
        make.bottom.mas_equalTo(-80);
        make.height.mas_equalTo(44);
        make.right.mas_equalTo(-20);
    }];
    
    if (self.userInfoModel.v == 1) { // 待处理
        
        goVerifyBtn.hidden = YES;
        iconView.image = [UIImage imageNamed:@"resumeState1"];
        flagLbl1.text = @"实名认证审核中，请耐心等待";
    }else if (self.userInfoModel.v == 3) { // 认证失败
    
        goVerifyBtn.hidden = YES;
        iconView.image = [UIImage imageNamed:@"resumeState2"];
        flagLbl1.text = @"实名认证失败，请重新提交或联系客服";
    }
}


#pragma mark - 获取数据
- (void)refreshPage
{
    [self getVerification];
    [self getHospitlList];
}

- (void)getVerification
{
    // 显示菊花
    // [SVProgressHUD show];
    
    [YAYINetWorking getWithURL:me_personalinfo param:nil finish:^(NSData *data, NSDictionary *dict, NSError *error) {
        if (error == nil) {
            YAYILog(@"返回：%@", dict);
            
            if (dict == nil || [dict isKindOfClass:[NSNull class]] || ![dict[@"status"] isEqualToString:@"success"]) {
                //                return;
            }else{
                self.userInfoModel.v = [dict[@"data"][@"v"] integerValue];
                [self setupSubView];
            }   
        }
        
        [SVProgressHUD dismiss];
    }];
}


- (void)getHospitlList
{
    [YAYINetWorking getWithURL:myHospital_url param:nil finish:^(NSData *data, NSDictionary *dict, NSError *error) {
        if (error == nil) {
            YAYILog(@"返回：%@", dict);
            
            if (dict == nil || [dict isKindOfClass:[NSNull class]] || ![dict[@"status"] isEqualToString:@"success"]) {
                return;
            }
            
            NSArray *dictArray = dict[@"data"];
            
            if (dictArray.count > 0) {
                self.hosAddress = dictArray[0][@"address"];
                self.hosName = dictArray[0][@"name"];
                self.hospitalNameLbl.text = self.hosName;
                self.addressLbl.text = self.hosAddress;
            }
        }
        
        // 取消显示hud
        // [SVProgressHUD dismiss];
    }];
}



#pragma mark - 点击事件
- (void)shareClick:(UIButton *)sender
{
    YAYILog(@"点击了分享");
    
    // 获取qrCodeView的截图
    
    UIGraphicsBeginImageContextWithOptions(self.qrCodeView.bounds.size, YES, 1);
    [self.qrCodeView.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *qrImg = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    
    YAYIShareView *shareView = [[YAYIShareView alloc] initWithDelegate:self];
    shareView.shareImage = qrImg;
    shareView.shareContent = @"雅同医生扫码关注！";
    [shareView show];
}


/**  去实名认证 */
- (void)onGoVerifyBtnClick:(UIButton *)sender
{
    
    YAYICertificationViewController *verifyVc = [[YAYICertificationViewController alloc] init];
    [self.navigationController pushViewController:verifyVc animated:YES];
}


#pragma mark - 工具方法
/**
 *  根据串生成二维码图片
 */
- (UIImage *)getQRCode:(NSString *)codeStr
{
    //1.创建滤镜
    CIFilter *filter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
    
    //2.恢复默认
    [filter setDefaults];
    
    //3.给滤镜添加数据
    NSString *dataString = codeStr;

    //将数据转换成NSData类型
    NSData *data = [dataString dataUsingEncoding:NSUTF8StringEncoding];
    
    //通过KVC设置滤镜的二维码输入信息
    [filter setValue:data forKey:@"inputMessage"];
    
    //4.获取输出的二维码图片（CIImage类型）
    CIImage *outImage = [filter outputImage];
    //将CIImage类型的图片装换成UIImage类型的图片
//    UIImage *image = [UIImage imageWithCIImage:outImage];
//    UIImage *image = [UIImage imageWithCIImage:outImage scale:20.0 orientation:UIImageOrientationUp];
    
    return [self createNonInterpolatedUIImageFormCIImage:outImage withSize:200];
}


/**
 *  放大bitmap
 */
- (UIImage *)createNonInterpolatedUIImageFormCIImage:(CIImage *)image withSize:(CGFloat) size {
    
    CGRect extent = CGRectIntegral(image.extent);
    
    CGFloat scale = MIN(size/CGRectGetWidth(extent), size/CGRectGetHeight(extent));
    
    // 创建bitmap;
    
    size_t width = CGRectGetWidth(extent) * scale;
    
    size_t height = CGRectGetHeight(extent) * scale;
    
    CGColorSpaceRef cs = CGColorSpaceCreateDeviceGray();
    
    CGContextRef bitmapRef = CGBitmapContextCreate(nil, width, height, 8, 0, cs, (CGBitmapInfo)kCGImageAlphaNone);
    
    CIContext *context = [CIContext contextWithOptions:nil];
    
    CGImageRef bitmapImage = [context createCGImage:image fromRect:extent];
    
    CGContextSetInterpolationQuality(bitmapRef, kCGInterpolationNone);
    
    CGContextScaleCTM(bitmapRef, scale, scale);
    
    CGContextDrawImage(bitmapRef, extent, bitmapImage);
    
    // 保存bitmap到图片
    CGImageRef scaledImage = CGBitmapContextCreateImage(bitmapRef);
    
    CGContextRelease(bitmapRef);
    
    CGImageRelease(bitmapImage);
    
    return [UIImage imageWithCGImage:scaledImage];
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
